require( '$d/css/common.less' );
require( './style.less' );
define( [
  'require',
  'jquery',
  'header',
  'message',
  'pagination',
  'bigwe_utils',
  'bootstrap',
  'nav',
  'bigwe_component',
  'constants',
  'api',
], function( require, $, header, ShowTitleMessage, util ) {
  var public_vars = public_vars || {},
    bc = require( 'bigwe_component' );
  var constants = require( 'constants' );
  var InterFace = require( 'api' );
  var param = {
    p: 1,
  };

  function tplt_lst() {
    var htm = '';
    $.ajax( {
      type: 'get',
      url: InterFace.TEMPLATE.GET_TEMPLATE_LIST,
      data: param,
      success: function( data ) {
        var data = eval( '(' + data + ')' );
        var many = data.data;
        if ( data.ret == 0 ) {
          $( '.total_number' ).text( many.count );
          for ( i in many.data ) {
            var alone = many.data[ i ];
            var h = alone.pic.match( /(?:http(?:s)?:\/\/)?(?:www\.)?(.*?)\./ )[ 1 ];

            htm += '<div><input type="checkbox" class="con_list_ckeck" cd="' + alone.tid + '">' +
              '<p>' + getLocalTime( alone.time ).format( "yyyy-MM-dd" ) + '</p>' +
              '<div class="tmpe_pew"><img src="' + ( ( h != 'img01' ) ? ( constants.surpportHostName + '/timthumb.php?w=200&src=' + alone.pic ) : ( alone.pic ) ) + '" alt="" onerror="this.src=\'http://img01.bigwe.com/template_default.png\'"><div class="tmpt_details"><p><span class="iconfont icon-dianzan"></span>&nbsp;<span class="count">0</span></p><p><span class="iconfont icon-collect"></span>&nbsp;<span class="count">0</span></p></div></div>' +
              '<p class="con_title" title="' + alone.title + '">' + ( ( alone.title == null || alone.title == "" || typeof( alone.title ) == "undefined" ) ? "" : alone.title ) + '</p>' +
              '<button type="button" class="pull-right delete_trash"><span class="glyphicon glyphicon-trash" data-toggle="tooltip" title="删除"></span></button><button type="button" class="pull-right create_edit"><span class="iconfont icon-chuangzuo" data-toggle="tooltip" title="编辑"></span></button><button type="button" class="pull-right mould_use"><span class="iconfont icon-queding" data-toggle="tooltip" title="使用"></span></button></div>';
          }
        } else {
          $( '.total_number' ).text( 0 );
          $( '.con_list' ).empty().append( '<p><span class="glyphicon glyphicon-flash" style="position: relative;top:3px;right:3px;"></span>您还没有模板！</p>' );
          return;
        }
        $( '.con_list' ).empty().append( htm );
        if ( !$( '.batch_selection' ).is( ':hidden' ) ) {
          public_vars.$contentList.find( '.con_list_ckeck' ).show();
        }
        $( "[data-toggle='tooltip']" ).tooltip();
        if ( public_vars.page ) {
          paging( many.count );
        }
      },
      complete: function() {
        ShowTitleMessage.hide();
      }
    } )
  }
  /*单选全选*/
  function check_change() {
    if ( $( this ).attr( 'name' ) == 'all' ) {
      if ( $( this )[ 0 ].checked ) {
        public_vars.$contentList.find( 'input[type="checkbox"]' ).prop( 'checked', true );
        $( '.batch_selection' ).find( 'button' ).removeAttr( 'disabled' );
        $( '.batch_selection' ).find( '.bat_check' ).text( $( '.con_list' ).find( ':checked' ).length + '篇' );
      } else {
        public_vars.$contentList.find( 'input[type="checkbox"]' ).removeAttr( 'checked' );
        $( '.batch_selection' ).find( 'button' ).prop( 'disabled', true );
        $( '.batch_selection' ).find( '.bat_check' ).text( '无' );
      }
    } else {
      var $checkAll = $( '.batch_selection' ).find( "input[type='checkbox']" );
      var graphLen = public_vars.$contentList.find( 'input[type="checkbox"]' ).length,
        checkLen = $( '.con_list' ).find( ':checked' ).length;
      if ( checkLen == 0 ) {
        $checkAll[ 0 ].indeterminate = false;
        $checkAll.removeAttr( 'checked' );
        $( '.batch_selection' ).find( 'button' ).prop( 'disabled', true );
        $( '.batch_selection' ).find( '.bat_check' ).text( '无' );
      } else {
        $( '.batch_selection' ).find( 'button' ).removeAttr( 'disabled' );
        $( '.batch_selection' ).find( '.bat_check' ).text( checkLen + '篇' );
        if ( graphLen != checkLen ) {
          $checkAll[ 0 ].indeterminate = true;
        } else {
          $checkAll[ 0 ].indeterminate = false;
          $checkAll.prop( 'checked', 'checked' );
        }
      }
    }
  }

  /*刪除*/
  function delte( e ) {
    e.stopPropagation();
    var $this = $( this );
    bc.deleteConfirmShowBottom( {
      obj: this,
      fun: function() {
        var object = "";
        if ( $this.hasClass( 'delete_trash' ) ) {
          $this.parent().remove();
          var object = $this.siblings( '.con_list_ckeck' ).attr( 'cd' );
        } else {
          public_vars.$contentList.find( 'input[type="checkbox"]' ).each( function() {
            if ( this.checked ) {
              if ( object.length > 1 ) {
                object += ",";
              }
              object += $( this ).attr( "cd" );
              $( this ).parent().remove();
            }
          } );
          public_vars.$allCheck[ 0 ].indeterminate = false;
          public_vars.$allCheck.removeAttr( 'checked' );
          $( '.batch_selection' ).find( 'button' ).prop( 'disabled', true );
          $this.parent().find( ".bat_check" ).text( '无' );
        }

        var chil_len = '';
        public_vars.$contentList.each( function() {
          chil_len = $( this ).children().length;
        } );
        if ( chil_len == 0 && param[ 'p' ] != 1 ) {
          // if ($('.search_input') != '') {
          //     param['title'] = '';
          //     $('.search_input').val('');
          // }
          param[ 'p' ] -= 1;
          public_vars.page = true;
        }

        $.ajax( {
          type: 'post',
          url: InterFace.TEMPLATE.DELETE_TEMPLATE,
          data: {
            tid: object
          },
          success: function( data ) {
            var data = eval( '(' + data + ')' );
            if ( !data.ret ) {
              ShowTitleMessage.show( '删除成功!', 1500 );
              public_vars.page = true;
              tplt_lst();
            } else {
              ShowTitleMessage.show( data.msg );
            }
          }
        } )
      }
    } )
  }

  /*分页*/
  function paging( j ) {
    if ( j > 16 ) {
      $( '.paging' ).show();
    } else {
      $( '.paging' ).hide();
    }
    var cur_page = param[ 'p' ] - 1;
    $( ".paging" ).pagination( j, {
      num_edge_entries: 0,
      items_per_page: 16,
      current_page: cur_page,
      prev_text: '上一页',
      next_text: '下一页',
      callback: function( _index, jq ) {
        if ( public_vars.page ) {
          public_vars.page = false;
          return;
        } else {
          param.p = _index + 1;
          tplt_lst();
        }
      }
    } );
  }

  function getLocalTime( nS ) {
    return new Date( parseInt( nS ) * 1000 );
  }

  Date.prototype.format = function( format ) {
    var o = {
      "M+": this.getMonth() + 1, // month
      "d+": this.getDate(), // day
      "h+": this.getHours(), // hour
      "m+": this.getMinutes(), // minute
      "s+": this.getSeconds(), // second
      "q+": Math.floor( ( this.getMonth() + 3 ) / 3 ), // quarter
      "S": this.getMilliseconds()
    }

    if ( /(y+)/.test( format ) ) {
      format = format.replace( RegExp.$1, ( this.getFullYear() + "" )
        .substr( 4 - RegExp.$1.length ) );
    }

    for ( var k in o ) {
      if ( new RegExp( "(" + k + ")" ).test( format ) ) {
        format = format.replace( RegExp.$1, RegExp.$1.length == 1 ? o[ k ] : ( "00" + o[ k ] ).substr( ( "" + o[ k ] ).length ) );
      }
    }
    return format;
  };
  ShowTitleMessage.show( '正在加载...' );
  public_vars.$body = $( "body" );
  public_vars.$contentContainer = public_vars.$body.find( ".main_left" );
  public_vars.$contentList = public_vars.$contentContainer.find( ".con_list" );

  public_vars.$batch = public_vars.$contentContainer.find( ".batch" );
  public_vars.$select = public_vars.$contentContainer.find( '.flr_btn' );
  public_vars.$search = public_vars.$contentContainer.find( '.search_btn' );

  public_vars.$allCheck = public_vars.$contentContainer.find( 'input[name="all"]' );
  // public_vars.$check                  = public_vars.$contentList.find('input[type="checkbox"]');

  public_vars.page = true;

  window.onerror = function() {
    ShowTitleMessage.show( '加载错误...' );
  }

  tplt_lst();

  /*批量管理*/
  public_vars.$batch.on( 'click', function() {
    if ( $( '.batch_selection' ).is( ':hidden' ) ) {
      $( ".con_hd_filter" ).hide();
      $( '.batch_selection,.con_list_ckeck' ).show();
      $( this ).text( '取消批量管理' );
    } else {
      $( ".con_hd_filter" ).show();
      $( '.batch_selection,.con_list_ckeck' ).hide();
      $( this ).text( '批量管理' );
    }
  } );

  /*多選*/
  public_vars.$allCheck.change( check_change );
  public_vars.$contentList.on( 'change', 'input[type="checkbox"]', check_change );

  /*删除*/
  public_vars.$contentContainer.on( 'click', '.delete_trash', delte );
  $( '.batch-del' ).on( 'click', delte );

  /*编辑*/
  public_vars.$contentContainer.on( 'click', '.create_edit', function() {
    var tid = $( this ).siblings( '.con_list_ckeck' ).attr( 'cd' );
    window.open( '/template?tid=' + tid );
  } );

  /*使用*/
  public_vars.$contentContainer.on( 'click', '.mould_use', function() {
    var tid = $( this ).siblings( '.con_list_ckeck' ).attr( 'cd' );
    window.open( '/edit_text?edit_type=1&template_id=' + tid );
  } );


  /*搜索*/
  public_vars.$search.click( function() {
    var value = $( "#search_text" ).val();
    param.title = value;
    param.p = 1;
    public_vars.page = true;
    tplt_lst();
  } );

  /*筛选*/
  public_vars.$select.change( function() {
    console.log( $( this ).val() );
  } );

  return null;
} );